package com.vnaloha.common.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.vnaloha.common.model.Gallery;
import com.vnaloha.util.CustomHibernateDaoSupport;

@Repository
public class GalleryDAOImpl extends CustomHibernateDaoSupport implements GalleryDAO{
	
	private Logger logger = LoggerFactory.getLogger(GalleryDAOImpl.class);

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.dao.GalleryDAO#get(int)
	 */
	@Override
	public Gallery get(int id) {
		Gallery gallery = getHibernateTemplate().get(Gallery.class, id);

		if (null != gallery) {
			return gallery;
		}
		logger.error("Error when get gallery by id " + id);
		return null;
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.dao.GalleryDAO#save(com.vnaloha.common.model.Gallery)
	 */
	@Override
	public boolean save(Gallery gallery) {
		try {
			getHibernateTemplate().save(gallery);
			return true;
		} catch (Exception e) {
			logger.debug("Error when save or update gallery: " + gallery);
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.dao.GalleryDAO#list(int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Gallery> list() {
		
		List<Gallery> list = null;
		try {
			list = getHibernateTemplate().find(" from Gallery order by id desc");
		} catch (HibernateException e) {
			logger.error("Error when get list gallery " + e, e);
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Gallery> list(int start, int max) {
		
		List<Gallery> list = null;
		try {
			String sql = " from Gallery order by id desc limit " + start + "," + max;
			list = getHibernateTemplate().find(sql, Gallery.class);
		} catch (HibernateException e) {
			logger.error("Error when get list gallery " + e, e);
		}
		return list;
	}

	/*
	 * (non-Javadoc)
	 * @see com.vnaloha.common.dao.GalleryDAO#delete(int)
	 */
	@Override
	public boolean delete(int id) {
		try {
			Gallery gallery = getHibernateTemplate().get(Gallery.class, id);
			if(null != gallery) {
				getHibernateTemplate().delete(gallery);
				return true;
			}
		} catch (Exception e) {
			logger.debug("Error when delete gallery " + e, e);
		}
		return false;
	}

}
